{% extends "base.html" %}

{% block title %}管理员座位管理{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-chair"></i> 管理员座位管理</h2>
                <div>
                    <button class="btn btn-info me-2" onclick="refreshSeats()">
                        <i class="fas fa-sync-alt"></i> 手动刷新
                    </button>
                    <a href="{{ url_for('admin') }}" class="btn btn-outline-primary">
                        <i class="fas fa-arrow-left"></i> 返回管理面板
                    </a>
                    <div class="mt-1">
                        <small class="text-muted">
                            <i class="fas fa-clock"></i> 自动刷新：每30秒
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 管理操作卡片 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-gradient-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-tools"></i> 管理操作</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-2">
                            <a href="{{ url_for('admin_face_recognition_page') }}" class="btn btn-danger btn-lg w-100" target="_blank">
                                <i class="fas fa-camera"></i> 人脸识别入馆
                            </a>
                        </div>
                        <div class="col-md-4 mb-2">
                            <button class="btn btn-info btn-lg w-100" onclick="refreshSeats()">
                                <i class="fas fa-sync-alt"></i> 刷新座位状态
                            </button>
                        </div>
                        <div class="col-md-4 mb-2">
                            <button class="btn btn-warning btn-lg w-100" onclick="exportData()">
                                <i class="fas fa-download"></i> 导出座位数据
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 座位状态统计 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card" style="background-color: #f8f9fa; border: 1px solid #dee2e6;">
                <div class="card-body text-center">
                    <i class="fas fa-check-circle fa-2x mb-2" style="color: #28a745;"></i>
                    <h4 id="availableCount" style="color: #28a745;">{{ available_count }}</h4>
                    <p style="color: #6c757d;">空闲座位</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card" style="background-color: #f8f9fa; border: 1px solid #dee2e6;">
                <div class="card-body text-center">
                    <i class="fas fa-clock fa-2x mb-2" style="color: #ffc107;"></i>
                    <h4 id="reservedCount" style="color: #ffc107;">{{ reserved_count }}</h4>
                    <p style="color: #6c757d;">已预约</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card" style="background-color: #f8f9fa; border: 1px solid #dee2e6;">
                <div class="card-body text-center">
                    <i class="fas fa-user fa-2x mb-2" style="color: #dc3545;"></i>
                    <h4 id="occupiedCount" style="color: #dc3545;">{{ occupied_count }}</h4>
                    <p style="color: #6c757d;">使用中</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card" style="background-color: #f8f9fa; border: 1px solid #dee2e6;">
                <div class="card-body text-center">
                    <i class="fas fa-chair fa-2x mb-2" style="color: #17a2b8;"></i>
                    <h4 id="totalCount" style="color: #17a2b8;">{{ total_count }}</h4>
                    <p style="color: #6c757d;">总座位数</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 楼层导航 -->
    <div class="row mb-4">
        <div class="col-12">
            <ul class="nav nav-pills justify-content-center" id="floor-tabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="all-tab" data-bs-toggle="pill" data-bs-target="#all-floors" type="button" role="tab">
                        <i class="fas fa-list"></i> 全部楼层
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor1-tab" data-bs-toggle="pill" data-bs-target="#floor1" type="button" role="tab">
                        <i class="fas fa-building"></i> 一楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor2-tab" data-bs-toggle="pill" data-bs-target="#floor2" type="button" role="tab">
                        <i class="fas fa-building"></i> 二楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor3-tab" data-bs-toggle="pill" data-bs-target="#floor3" type="button" role="tab">
                        <i class="fas fa-building"></i> 三楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor4-tab" data-bs-toggle="pill" data-bs-target="#floor4" type="button" role="tab">
                        <i class="fas fa-building"></i> 四楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor5-tab" data-bs-toggle="pill" data-bs-target="#floor5" type="button" role="tab">
                        <i class="fas fa-building"></i> 五楼
                    </button>
                </li>
            </ul>
        </div>
    </div>

    <!-- 座位列表 -->
    <div class="tab-content" id="floor-content">
        <!-- 全部楼层 -->
        <div class="tab-pane fade show active" id="all-floors" role="tabpanel">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-table"></i> 所有座位状态</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="seatsTable" style="color: #212529;">
                            <thead class="table-dark">
                                <tr>
                                    <th>楼层</th>
                                    <th>座位号</th>
                                    <th>状态</th>
                                    <th>使用者</th>
                                    <th>学号</th>
                                    <th>预约时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody style="color: #212529; font-weight: 500;">
                                {% for seat in seats %}
                                <tr class="floor-{{ seat.floor }}">
                                    <td><span class="badge bg-primary">{{ seat.floor }}楼</span></td>
                                    <td><strong style="color: #0d6efd; font-size: 1.1em;">{{ seat.seat_number }}</strong></td>
                                    <td>
                                    {% if seat.reservation_status == '使用中' or (seat.reservation_status == 'completed' and seat.name) %}
                                        <span class="badge bg-danger" style="color: #ffffff; font-weight: 600;">使用中</span>
                                    {% elif seat.reservation_status == '已预约' or seat.reservation_status == 'active' %}
                                        <span class="badge bg-warning" style="color: #000000; font-weight: 600;">已预约</span>
                                    {% else %}
                                        <span class="badge bg-success" style="color: #ffffff; font-weight: 600;">空闲</span>
                                    {% endif %}
                                </td>
                                    <td>
                                        {% if seat.reservation_status == '使用中' or (seat.reservation_status == 'completed' and seat.name) or seat.reservation_status == '已预约' or seat.reservation_status == 'active' %}
                                            <span style="color: #198754; font-weight: 600;">{{ seat.name or '-' }}</span>
                                        {% else %}
                                            <span style="color: #6c757d; font-weight: 400;">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if seat.reservation_status == '使用中' or (seat.reservation_status == 'completed' and seat.name) or seat.reservation_status == '已预约' or seat.reservation_status == 'active' %}
                                            <span style="color: #6f42c1; font-weight: 500;">{{ seat.student_id or '-' }}</span>
                                        {% else %}
                                            <span style="color: #6c757d; font-weight: 400;">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if (seat.reservation_status == '使用中' or (seat.reservation_status == 'completed' and seat.name) or seat.reservation_status == '已预约' or seat.reservation_status == 'active') and seat.start_time_slot and seat.end_time_slot %}
                                            {{ seat.start_time_slot }} - {{ seat.end_time_slot }}
                                            <br><small style="color: #6c757d; font-weight: 500;">{{ seat.reservation_date.strftime('%Y-%m-%d') if seat.reservation_date else '' }}</small>
                                        {% else %}
                                            <span style="color: #6c757d; font-weight: 400;">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-info" onclick="manageSeat('{{ seat.id }}', '{{ seat.floor }}', '{{ seat.seat_number }}', '{% if seat.reservation_status == '使用中' or (seat.reservation_status == 'completed' and seat.name) %}occupied{% elif seat.reservation_status == '已预约' or seat.reservation_status == 'active' %}reserved{% else %}available{% endif %}')">
                                            <i class="fas fa-cog"></i> 管理
                                        </button>
                                        {% if seat.reservation_status == '使用中' or (seat.reservation_status == 'completed' and seat.name) or seat.reservation_status == '已预约' or seat.reservation_status == 'active' %}
                                        <button class="btn btn-sm btn-outline-danger" onclick="cancelReservation('{{ seat.id }}', '{{ seat.seat_number }}')">
                                            <i class="fas fa-times"></i> 取消
                                        </button>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 各楼层分页 -->
        {% for floor in [1, 2, 3, 4, 5] %}
        <div class="tab-pane fade" id="floor{{ floor }}" role="tabpanel">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-building"></i> {{ floor }}楼座位状态</h5>
                </div>
                <div class="card-body">
                    <div class="seat-grid">
                        {% for seat in seats %}
                            {% if seat.floor == floor %}
                            <div class="seat-item">
                                {% if seat.name %}
                                <!-- 已预约座位 -->
                                <div class="seat-card occupied" onclick="manageSeat('{{ seat.id }}', '{{ seat.seat_number }}')">
                                    <div class="seat-number">{{ seat.seat_number }}</div>
                                    <div class="seat-user">{{ seat.name }}</div>
                                    <div class="seat-time">
                                        {% if seat.start_time %}
                                            {{ seat.start_time.strftime('%H:%M') }}
                                        {% endif %}
                                    </div>
                                    <div class="seat-status">已预约</div>
                                </div>
                                {% else %}
                                <!-- 空闲座位 -->
                                <div class="seat-card available" onclick="manageSeat('{{ seat.id }}', '{{ seat.seat_number }}')">
                                    <div class="seat-number">{{ seat.seat_number }}</div>
                                    <div class="seat-status">空闲</div>
                                </div>
                                {% endif %}
                            </div>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

<style>
.seat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 15px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 10px;
}

.seat-item {
    display: flex;
    justify-content: center;
}

.seat-card {
    width: 100px;
    height: 80px;
    border-radius: 10px;
    border: 2px solid;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.seat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.seat-card.available {
    background: #d4edda;
    border-color: #28a745;
    color: #155724;
}

.seat-card.occupied {
    background: #f8d7da;
    border-color: #dc3545;
    color: #721c24;
}

.seat-number {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 2px;
}

.seat-user {
    font-size: 10px;
    color: #666;
    margin-bottom: 1px;
}

.seat-time {
    font-size: 9px;
    color: #888;
}

.seat-status {
    font-size: 11px;
    color: #666;
}

.nav-pills .nav-link {
    border-radius: 25px;
    margin: 0 5px;
    transition: all 0.3s ease;
}

.nav-pills .nav-link.active {
    background: linear-gradient(45deg, #007bff, #0056b3);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,123,255,0.3);
}

.card {
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-radius: 15px;
}

.card-header {
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    border-bottom: 1px solid #dee2e6;
    border-radius: 15px 15px 0 0 !important;
}

@media (max-width: 768px) {
    .seat-grid {
        grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
        gap: 10px;
        padding: 15px;
    }
    
    .seat-card {
        width: 80px;
        height: 60px;
        font-size: 10px;
    }
    
    .seat-number {
        font-size: 12px;
    }
}
</style>

<script>
// 页面加载时启动自动刷新
document.addEventListener('DOMContentLoaded', function() {
    // 启动自动刷新
    startAutoRefresh();
    
    // 添加状态选择事件监听器
    const seatStatusSelect = document.getElementById('seatStatus');
    if (seatStatusSelect) {
        seatStatusSelect.addEventListener('change', function() {
            const studentSection = document.getElementById('studentInfoSection');
            if (this.value === 'reserved' || this.value === 'occupied') {
                studentSection.style.display = 'block';
            } else {
                studentSection.style.display = 'none';
                document.getElementById('studentId').value = '';
            }
        });
    }
});

// 全局变量存储当前操作的座位信息
let currentSeatId = null;
let currentSeatNumber = null;

// 管理座位状态
function manageSeat(seatId, seatNumber) {
    currentSeatId = seatId;
    currentSeatNumber = seatNumber;
    
    // 设置座位信息
    document.getElementById('seatInfo').textContent = `座位号: ${seatNumber}`;
    
    // 重置表单
    document.getElementById('seatStatus').value = 'available';
    document.getElementById('studentId').value = '';
    document.getElementById('studentInfoSection').style.display = 'none';
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('seatStatusModal'));
    modal.show();
}

// 更新座位状态
function updateSeatStatus() {
    const seatId = window.currentSeatId;
    const newStatus = document.getElementById('seatStatus').value;
    const studentId = document.getElementById('studentId').value;
    
    // 验证必填字段
    if ((newStatus === 'reserved' || newStatus === 'occupied') && !studentId) {
        alert('请输入学生ID');
        return;
    }
    
    // 发送更新请求
    fetch('/admin/update_seat_status', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            seat_id: seatId,
            status: newStatus,
            student_id: studentId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('seatStatusModal'));
            modal.hide();
            
            // 刷新页面
            location.reload();
        } else {
            alert(data.error || '更新失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('更新失败，请重试');
    });
}





// 自动刷新变量
let autoRefreshInterval = null;

// 启动自动刷新
function startAutoRefresh() {
    // 每30秒刷新一次座位状态
    if (!autoRefreshInterval) {
        autoRefreshInterval = setInterval(refreshSeats, 30000);
    }
}

// 刷新座位状态
function refreshSeats() {
    // 重新加载页面来获取最新的座位状态
    window.location.reload();
}

// 停止自动刷新
function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
    }
}

// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});



// 管理座位
function manageSeat(seatId, floor, seatNumber, currentStatus) {
    // 设置模态框中的座位信息
    document.getElementById('seatInfo').textContent = `${floor}楼 - 座位${seatNumber}`;
    
    // 设置当前状态
    document.getElementById('seatStatus').value = currentStatus;
    
    // 根据状态显示/隐藏学生ID输入框
    const studentSection = document.getElementById('studentInfoSection');
    if (currentStatus === 'reserved' || currentStatus === 'occupied') {
        studentSection.style.display = 'block';
    } else {
        studentSection.style.display = 'none';
    }
    
    // 存储座位ID供后续使用
    window.currentSeatId = seatId;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('seatStatusModal'));
    modal.show();
}

// 取消预约
function cancelReservation(seatId, seatNumber) {
    if (confirm(`确定要取消座位 ${seatNumber} 的预约吗？`)) {
        fetch(`/cancel_reservation/${seatId}`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert(data.message || '取消失败，请重试');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('取消失败，请重试');
        });
    }
}

// 刷新座位状态
function refreshSeats() {
    // 显示刷新提示
    const refreshBtn = document.querySelector('button[onclick="refreshSeats()"]');
    if (refreshBtn) {
        const originalText = refreshBtn.innerHTML;
        refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中...';
        refreshBtn.disabled = true;
        
        setTimeout(() => {
            location.reload();
        }, 500);
    } else {
        location.reload();
    }
}

// 导出数据
function exportData() {
    alert('导出功能开发中...');
}

// 楼层筛选
document.querySelectorAll('[data-bs-toggle="pill"]').forEach(tab => {
    tab.addEventListener('shown.bs.tab', function(e) {
        const target = e.target.getAttribute('data-bs-target');
        if (target === '#all-floors') {
            // 显示所有行
            document.querySelectorAll('#seatsTable tbody tr').forEach(row => {
                row.style.display = '';
            });
        } else {
            // 只显示对应楼层的行
            const floor = target.replace('#floor', '');
            document.querySelectorAll('#seatsTable tbody tr').forEach(row => {
                if (row.classList.contains(`floor-${floor}`)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
    });
});
</script>

<!-- 座位状态修改模态框 -->
<div class="modal fade" id="seatStatusModal" tabindex="-1" aria-labelledby="seatStatusModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="seatStatusModalLabel">
                    <i class="fas fa-cog"></i> 修改座位状态
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label"><strong>座位信息</strong></label>
                    <p id="seatInfo" class="text-muted"></p>
                </div>
                <div class="mb-3">
                    <label for="seatStatus" class="form-label"><strong>选择新状态</strong></label>
                    <select class="form-select" id="seatStatus">
                        <option value="available">空闲</option>
                        <option value="reserved">已预约</option>
                        <option value="occupied">使用中</option>
                    </select>
                </div>
                <div class="mb-3" id="studentInfoSection" style="display: none;">
                    <label for="studentId" class="form-label"><strong>学生ID</strong></label>
                    <input type="text" class="form-control" id="studentId" placeholder="请输入学生ID">
                    <div class="form-text">设置为已预约或使用中时需要指定学生</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="btn btn-primary" onclick="updateSeatStatus()">
                    <i class="fas fa-save"></i> 确认修改
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}